#pragma once
#include <queue>
#include <thread>
#include "Msg.h"
#include <ConnWriter.h>

using namespace std;

extern "C" {
    #include "../3rd/lua-5.4.3/src/lua.h"
    #include "../3rd/lua-5.4.3/src/lauxlib.h"
    #include "../3rd/lua-5.4.3/src/lualib.h"
}

class Service {
    public:
        //唯一id
        uint32_t id;
        //类型
        shared_ptr<string> type;
        //是否正在退出
        bool isExiting = false;
        //消息队列和锁
        queue<shared_ptr<BaseMsg>> msgQueue;
        pthread_spinlock_t queueLock;

        bool inGlobal = false;
        pthread_spinlock_t inGlobalLock;
        // unordered_map<int, shared_ptr<ConnWriter>> writers;

    public:
        //构造和析构函数
        Service();
        ~Service();
        //回调函数（编写服务逻辑）
        void OnInit();
        void OnMsg(shared_ptr<BaseMsg> msg);
        void OnExit();
        //插入消息
        void PushMsg(shared_ptr<BaseMsg> msg);
        //执行消息
        bool ProcessMsg();
        void ProcessMsgs(int max);
        void SetInGlobal(bool isIn);
    private:
        shared_ptr<BaseMsg> PopMsg();
        void OnServiceMsg(shared_ptr<ServiceMsg> msg);
        void OnAcceptMsg(shared_ptr<SocketAcceptMsg> msg);
        void OnRWMsg(shared_ptr<SocketRWMsg> msg);
        void OnSocketData(int fd, const char* buff, int len);
        void OnSocketWritable(int fd);
        void OnSocketClose(int fd);
        lua_State *luaState;
};